What is @whatwg-node/fetch?
@whatwg-node/fetch is an npm package that provides a WHATWG Fetch API implementation for Node.js. It allows developers to use the familiar Fetch API, which is standard in web browsers, in a Node.js environment. This package is useful for making HTTP requests, handling responses, and working with various types of data formats.
What are @whatwg-node/fetch's main functionalities?
Basic Fetch Request
This feature allows you to make a basic HTTP GET request to a specified URL and handle the response. The example fetches a post from a placeholder API and logs the JSON response.
const fetch = require('@whatwg-node/fetch');
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
POST Request with JSON Body
This feature allows you to make an HTTP POST request with a JSON body. The example sends a new post to the placeholder API and logs the JSON response.
const fetch = require('@whatwg-node/fetch');
const data = { title: 'foo', body: 'bar', userId: 1 };
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Handling Different Response Types
This feature demonstrates how to handle different response types and errors. The example checks if the response is OK before parsing it as JSON, and throws an error if the response is not OK.
const fetch = require('@whatwg-node/fetch');
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Network response was not ok');
}
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Other packages similar to @whatwg-node/fetch
node-fetch
node-fetch is a lightweight module that brings `window.fetch` to Node.js. It is widely used and has a similar API to the Fetch API in browsers. Compared to @whatwg-node/fetch, node-fetch is more mature and has a larger user base.
axios
axios is a promise-based HTTP client for Node.js and the browser. It provides a more feature-rich API compared to the Fetch API, including request and response interceptors, automatic JSON transformation, and more. It is more versatile but also more complex than @whatwg-node/fetch.
got
got is a human-friendly and powerful HTTP request library for Node.js. It supports many advanced features like retries, streams, and hooks. Compared to @whatwg-node/fetch, got offers more advanced features and better error handling.